<?php
/**
 * Created by PhpStorm.
 * User: bzg
 * Date: 2019/12/2
 * Time: 16:56
 */

namespace App\Extend\SysExtend\Command;


use EasySwoole\EasySwoole\Command\CommandInterface;

/**
 * 生成控制器
 * Class Controller
 * @package App\Extend\SysExtend\Command
 */
class Router implements CommandInterface
{

    public function commandName(): string
    {
        // TODO: Implement commandName() method.
        return 'make:router';
    }

    public function exec(array $args): ?string
    {
        // 生成控制器，控制器目录App/HttpController, 参数就是控制器的路径和名称
        $base_path = EASYSWOOLE_ROOT . '/App/Router/';
        if(empty($args[0])) {
            return '<error> please input router file name';
        }
        // 判断文件是否存在
        if(is_file($base_path . $args[0] . '.php')) {
            return '<error> router already existed!';
        }

        // 分开路径和路由名
        $c_arr = explode('/', $args[0]);

        // 首字母大写
        foreach ($c_arr as &$v) {
            $v = ucfirst($v);
        }

        if(count($c_arr) == 1) {
            $dir = '';
            $file = $c_arr[0];
        }else{
            $file = array_pop($c_arr);
            $dir = implode('/',$c_arr);
        }

        // 创建文件夹
        if(!is_dir($base_path . $dir)) {
            mkdir($base_path . $dir, 0777, true);
        }

        // 组装命名空间
        $namespace = $dir ? '\\' . str_replace('/','\\', $dir) : '';


        // 写入文件
        $content = <<<EOF
<?php

namespace App\Router{%namespace%};


use FastRoute\RouteCollector;

class {%class_name%}
{
    public function index(RouteCollector \$routeCollector)
    {
        // \$routeCollector->get('/','/Index/index');
    }
}
EOF;
        $content = str_replace('{%namespace%}', $namespace, $content);
        $content = str_replace('{%class_name%}', $file, $content);
        file_put_contents($base_path . $dir . '/' . $file . '.php', $content);
        return '<success> create router success!';
    }

    public function help(array $args): ?string
    {
        // TODO: Implement help() method.
        return 'auto create router';
    }
}